package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import luanvan.app.foodnote.library.IconContextMenu;
import luanvan.app.foodnote.library.JSONParser;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;


public class FoodSearchActivity extends ListActivity{
	 
	 private ProgressDialog pDialog;
	 
	 private JSONParser jsonParser = new JSONParser();
	 
	 private EditText EditSearch;
	 private Button btnSearchName;
	 private Button btnSearchCity;
	 private TextView tv;
	
	 private final int CONTEXT_MENU_ID = 1;
     private IconContextMenu iconContextMenu = null;
     
     private final int MENU_ITEM_1_ACTION = 1;
     private final int MENU_ITEM_2_ACTION = 2;
     private final int MENU_ITEM_3_ACTION = 3;
     private final int MENU_ITEM_4_ACTION = 4;
     
     private String fid, lat, lng;
     
     ArrayList<HashMap<String, String>> foodsList;
     
     private static final String url_search_food_name = "http://10.0.2.2/foodnote/search_foods.php";
     
     //private static final String url_search_food_name = "http://192.168.0.119/foodnote/search_foods.php";
     
     // JSON Node names
     private static final String TAG_SUCCESS = "success";
     private static final String TAG_FOODS = "foods";
     private static final String TAG_ID = "id";
     private static final String TAG_NAME = "TEN_MON_AN";
     private static final String TAG_ADDRESS = "DIA_CHI";
     private static final String TAG_LAT = "LATITUDE";
     private static final String TAG_LNG = "LONGITUDE";
     
     private static final String TAG_SEARCH_NAME = "search_food_name";
     private static final String TAG_SEARCH_ADDRESS = "search_food_address";
     
     // products JSONArray
     JSONArray foods = null;
     
    @Override 
	public void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_LEFT_ICON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_search);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.list_searches);

        EditSearch = (EditText)findViewById(R.id.EditSearch);
        btnSearchName = (Button)findViewById(R.id.SearchFood);
        btnSearchCity = (Button)findViewById(R.id.SearchCity);
        
        foodsList = new ArrayList<HashMap<String,String>>(); 
        tv = (TextView) findViewById(R.id.txtFound);
        final ListView listView = getListView(); 
        
        btnSearchName.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!tv.getText().toString().isEmpty())
					tv.setText("");
				foodsList.clear();
				if(EditSearch.getText().toString().isEmpty())
					alert(1);
				else {
					String edtSearch = EditSearch.getText().toString();
					new SearchFoodName().execute(edtSearch);
				}
			}
		});
        
        btnSearchCity.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!tv.getText().toString().isEmpty())
					tv.setText("");
				foodsList.clear();
				if(EditSearch.getText().toString().isEmpty())
					alert(2);
				else {
					String edtSearch = EditSearch.getText().toString();
					new SearchFoodAddress().execute(edtSearch);
				}
			}
		});
        
        registerForContextMenu(getListView());
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				fid = ((TextView)view.findViewById(R.id.fid)).getText().toString();
				lat = ((TextView) view.findViewById(R.id.lat)).getText().toString();
				lng = ((TextView) view.findViewById(R.id.lng)).getText().toString();
				openContextMenu(view);
				//showDialog(CONTEXT_MENU_ID);
			}
		});
		//this.subMenu();
	}
	
	private void subMenu(){
		 Resources res = getResources();
		 iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
		 iconContextMenu.addItem(res, "Cập Nhật", R.drawable.update, MENU_ITEM_1_ACTION);
		 iconContextMenu.addItem(res, "Món Ăn Xung Quanh", R.drawable.food_around, MENU_ITEM_2_ACTION);
		 iconContextMenu.addItem(res, "Hiển Thị Trên Bản Đồ", R.drawable.showmap, MENU_ITEM_3_ACTION);
		 iconContextMenu.addItem(res, "Chỉ Đường", R.drawable.direction, MENU_ITEM_4_ACTION);
       
		 iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			 public void onClick(int menuId) {
				 switch(menuId) {
				 case MENU_ITEM_1_ACTION:
					 Intent intentFoodPlace = new Intent(FoodSearchActivity.this, EditFoodActivity.class);
					 intentFoodPlace.putExtra(TAG_ID, fid);
					 //Log.d("FOOD_ID", fid);
					 startActivityForResult(intentFoodPlace, 100);
					 break;
               
				 case MENU_ITEM_2_ACTION:
					 Intent googlePlaces = new Intent(FoodSearchActivity.this, GooglePlacesActivity.class);
					 googlePlaces.putExtra(TAG_LAT, Double.valueOf(lat));
                	 googlePlaces.putExtra(TAG_LNG, Double.valueOf(lng));
					 startActivity(googlePlaces);
					 break;
				 case MENU_ITEM_3_ACTION:
					 Intent googleMaps = new Intent(FoodSearchActivity.this, LocationActivity.class);
					 googleMaps.putExtra(TAG_LAT, Double.valueOf(lat));
                	 googleMaps.putExtra(TAG_LNG, Double.valueOf(lng));
					 startActivity(googleMaps);
           			 break;
				 case MENU_ITEM_4_ACTION:
					 Intent direction = new Intent(FoodSearchActivity.this, DirectionsActivity.class);
					 direction.putExtra(TAG_LAT, Double.valueOf(lat));
                	 direction.putExtra(TAG_LNG, Double.valueOf(lng));
					 startActivity(direction);
					 break;
                }
			 }

       });
	 }
	
	private void alert(final int i){
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
	    final EditText input = new EditText(this);
	    
	    //alert.setTitle("Tìm kiếm");
	    alert.setMessage("Nhập vào từ khóa cần tìm");
	    alert.setView(input);
	    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            String value = input.getText().toString().trim();
	          
	            if(!value.isEmpty()){
	            	EditSearch.setText(value);
	            	if(i == 1)
		            	
	            		new SearchFoodName().execute(value);
		            if(i == 2)
		            	new SearchFoodAddress().execute(value);
	            }
	            
	            //Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
	        }
	    });

	    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            dialog.cancel();
	        }
	    });
	    alert.show(); 
	}
	/**
	 * @author quanghoang
	 * Tim mon an theo ten
	 */
	class SearchFoodName extends AsyncTask<String, Void, String>{

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(FoodSearchActivity.this);
            pDialog.setTitle("Please wait");
            pDialog.setMessage("Đang tìm...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		
		@Override
		protected String doInBackground(String... args) {
			String getValue = args[0];
			//String txtSearch = EditSearch.getText().toString();
			Log.d("Text Search", getValue);
			
		
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			params.add(new BasicNameValuePair(TAG_SEARCH_NAME, getValue));
			
			JSONObject json = jsonParser.makeHttpRequest(url_search_food_name, "GET", params);

			Log.d("Seach Name Food", json.toString());
			
			try {
				int success = json.getInt(TAG_SUCCESS);
				if(success == 1){
					foods = json.getJSONArray(TAG_FOODS);
					for(int i = 0; i < foods.length(); i++){
						JSONObject c = foods.getJSONObject(i);
						
						String id = c.getString(TAG_ID);
						String name = c.getString(TAG_NAME);
						String address = c.getString(TAG_ADDRESS);
						//String city = c.getString(TAG_CITY);
						
						HashMap<String, String> map = new HashMap<String, String>();
						
						map.put(TAG_ID, id);
						map.put(TAG_NAME, name);
						map.put(TAG_ADDRESS, address);
						//map.put(TAG_CITY, city);
						
						foodsList.add(map);
					}
				}
				else if(success == 0) {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							String txtFound = "Không tìm thấy món ăn nào. Vui lòng tìm lại!";
							tv.setText(txtFound);
						}
					});
					
				}
			} catch (JSONException e) {
                e.printStackTrace();
            }
			return null;
		}
		protected void onPostExecute(String file_url) {
       	 pDialog.dismiss();
       	 runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					/**
                    * Updating parsed JSON data into ListView
                    * */
                   ListAdapter adapter = new SimpleAdapter(
                           FoodSearchActivity.this, foodsList,
                           R.layout.row, new String[] { TAG_ID, TAG_NAME, TAG_ADDRESS},
                           new int[] {R.id.fid, R.id.foodname, R.id.address});
                   // updating listview
                   setListAdapter(adapter);
					
				}
			});
       }
	}
	/**
	 * 
	 * @author quanghoang
	 * Tim mon an theo dia chi
	 */
	class SearchFoodAddress extends AsyncTask<String, String, String>{

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(FoodSearchActivity.this);
            pDialog.setTitle("Please wait");
            pDialog.setMessage("Đang tìm...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		@Override
		protected String doInBackground(String... args) {
			String txtSearch = args[0];
			
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(TAG_SEARCH_ADDRESS, txtSearch));
			
			JSONObject json = jsonParser.makeHttpRequest(url_search_food_name, "GET", params);
			Log.d("Seach Address Food", json.toString());
			
			try {
				int success = json.getInt(TAG_SUCCESS);
				if(success == 1){
					foods = json.getJSONArray(TAG_FOODS);
					for(int i = 0; i < foods.length(); i++){
						JSONObject c = foods.getJSONObject(i);
						
						String id = c.getString(TAG_ID);
						String name = c.getString(TAG_NAME);
						String address = c.getString(TAG_ADDRESS);
						//String city = c.getString(TAG_CITY);
						
						HashMap<String, String> map = new HashMap<String, String>();
						
						map.put(TAG_ID, id);
						map.put(TAG_NAME, name);
						map.put(TAG_ADDRESS, address);
						//map.put(TAG_CITY, city);
						
						foodsList.add(map);
					}
				}
				else if(success == 0) {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							String txtFound = "Không tìm thấy món ăn nào. Vui lòng tìm lại!";
							tv.setText(txtFound);
						}
					});
				}
			} catch (JSONException e) {
                e.printStackTrace();
            }
			
			return null;
		}
		protected void onPostExecute(String file_url) {
	       	 pDialog.dismiss();
	       	 runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						/**
	                    * Updating parsed JSON data into ListView
	                    * */
	                   ListAdapter adapter = new SimpleAdapter(
	                           FoodSearchActivity.this, foodsList,
	                           R.layout.row, new String[] { TAG_ID, TAG_NAME, TAG_ADDRESS},
	                           new int[] {R.id.fid, R.id.foodname, R.id.address});
	                   // updating listview
	                   setListAdapter(adapter);
						
					}
				});
	       }
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Tùy chọn");
		menu.setHeaderIcon(R.drawable.submenu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
	}
	@Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Long id = getListAdapter().getItemId(info.position);
        Log.d("id = ", String.valueOf(id));
        switch (item.getItemId()) {
        case R.id.update:
        	Intent intentFoodPlace = new Intent(FoodSearchActivity.this, EditFoodActivity.class);
			intentFoodPlace.putExtra(TAG_ID, fid);
			Log.d("FOOD_ID", fid);
			startActivityForResult(intentFoodPlace, 100);
            return true;

        case R.id.food_places:
        	Intent googlePlaces = new Intent(FoodSearchActivity.this, GooglePlacesActivity.class);
       	 	googlePlaces.putExtra(TAG_LAT, Double.valueOf(lat));
       	 	googlePlaces.putExtra(TAG_LNG, Double.valueOf(lng));
       	 	startActivity(googlePlaces);
            return true;

        case R.id.direction:
        	Intent direction = new Intent(FoodSearchActivity.this, DirectionsActivity.class);
       	 	direction.putExtra(TAG_LAT, Double.valueOf(lat));
       	 	direction.putExtra(TAG_LNG, Double.valueOf(lng));
       	 	startActivity(direction);
        	return true;
        
        }
        return(super.onOptionsItemSelected(item));
    } 
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId()==R.id.setting){
			startActivity(new Intent(FoodSearchActivity.this, ShowSettingActivity.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
		
	}
	@SuppressWarnings("deprecation")
	@Override
    protected Dialog onCreateDialog(int id) {
        if (id == CONTEXT_MENU_ID) {
                return iconContextMenu.createMenu("Menu");
        }
        return super.onCreateDialog(id);
    }
	
	
}
